package cn.tangwei.org.service.impl;

import cn.tangwei.basic.service.impl.BaseServiceImpl;
import cn.tangwei.basic.utils.MD5Utils;
import cn.tangwei.basic.utils.PageList;
import cn.tangwei.basic.utils.StrUtils;
import cn.tangwei.org.domain.Employee;
import cn.tangwei.org.mapper.EmployeeMapper;
import cn.tangwei.org.query.EmployeeQuery;
import cn.tangwei.org.service.IEmployeeService;
import cn.tangwei.user.constants.UserConstants;
import cn.tangwei.user.domain.LoginInfo;
import cn.tangwei.user.mapper.LoginInfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {
    // 基本的CRUD 分页加高级查询 批量删除通过继承BaseServiceImpl得到
    // 自己写的自定义方法不能抽取
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LoginInfoMapper loginInfoMapper;

    /**
     *  重写添加方法，再添加的时候能在logininfo表里有数据，方便登录，级联添加
     * @param employee
     */
    @Override
    public void add(Employee employee) {
        initEmployee(employee);
        LoginInfo loginInfo = employee2LoginInfo(employee);
        loginInfoMapper.save(loginInfo);
        employee.setLogininfo_id(loginInfo.getId());
        employeeMapper.save(employee);
    }

    /**
     * 获取到一个LoginInfo对象
     * @param employee
     * @return
     */
    private LoginInfo employee2LoginInfo(Employee employee) {
        LoginInfo loginInfo = new LoginInfo();
        // 利用属性名同名原则，将employee复制到loginInfo
        BeanUtils.copyProperties(employee, loginInfo);
        return loginInfo;
    }

    private void initEmployee(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        // 使用盐值获取加密之后的密码
        String md5 = MD5Utils.encrypByMd5(UserConstants.BUSINESS_REGISTER_PREFIX + salt);
        employee.setSalt(salt);
        employee.setPassword(md5);
    }

    /**
     * 重写修改方法，再修改的时候能在logininfo表里有数据一起修改
     * @param employee
     */
    @Override
    public void update(Employee employee) {
        LoginInfo loginInfo = employee2LoginInfo(employee);
        loginInfoMapper.update(loginInfo);
        employeeMapper.update(employee);
    }

    /**
     * 重写删除方法，再修改的时候能在logininfo表里有数据一起删除
     * @param id
     */
    @Override
    public void delete(Long id) {
        Employee employee = employeeMapper.queryById(id);
        loginInfoMapper.remove(employee.getLogininfo_id());
        employeeMapper.remove(id);
    }
}


